import md5 from 'crypto-js/md5';

export const handle = async (apiUrl, minutes = 1, params = null, isCache = true) => {
    const cacheTime = new Date().getTime() + minutes * 60 * 1000;
    const cacheKey = params ? md5(apiUrl + JSON.stringify(params)) : apiUrl;
    let store = null;
    if (isCache) {
        store = SessionStore.get(cacheKey);
    }
    if (!store) {
        store = await API.get(apiUrl, {params});
        SessionStore.set(cacheKey, store, cacheTime);
    }
    return store;
};

/**
 * import {uploadToken} from 'api/Cache'
 * @returns {Promise<*>}
 * @constructor
 */
export const uploadToken = (drive, url) => handle(url, 2, {drive});

/**
  * [获取类目]
  * import {getCategorise} from 'api/Cache'
  * @param  {String} use [用途, cascader: 级联选择, null: 类目的一维数组]
  * @returns {Promise.<void>}
  */
import {formatCategorise} from '../config/parameter';
import cloneDeep from 'lodash/cloneDeep';

export const getCategorise = async (use = null) => {
    let store = SessionStore.get('categorise');
    let format = SessionStore.get('formatCategorise');

    if (!store || !format) {
        store = await API.get('applications/categories');
        SessionStore.set('categorise', store);

        format = formatCategorise(cloneDeep(store), null);
        SessionStore.set('formatCategorise', format);
    }
    if (use === 'cascader') return store;
    return format;
};

export const getHelpCategorise = async (use = null) => {
    let store = SessionStore.get('helpCategorise');
    let format = SessionStore.get('formatHelpCategorise');

    if (!store || !format) {
        store = await API.get('categories/help');
        SessionStore.set('helpCategorise', store);

        format = formatCategorise(cloneDeep(store), null);
        SessionStore.set('formatHelpCategorise', format);
    }
    if (use === 'cascader') return store;
    return format;
};